﻿using System;
using Nofs.Net.Common.Interfaces.Library;
using biz.ritter.javapi.util;
using biz.ritter.javapi.lang;
using biz.ritter.javapi.io;
using biz.ritter.javapi.net;

namespace Nofs.Net.nofs.stocks
{

    //@RootFolderObject
    //@DomainObject
    //@FolderObject(CanAdd=false, CanRemove=false)
    public class Portfolio
    {

        private IDomainObjectContainerManager _containerManager;
        private LinkedList<Stock> _stocks;

        public Portfolio()
        {
            _stocks = new LinkedList<Stock>();
        }

        //@NeedsContainerManager
        public void setContainerManager(IDomainObjectContainerManager manager)
        {
            _containerManager = manager;
        }

        //@FolderObject(CanAdd=true, CanRemove=true)
        public LinkedList<Stock> getStocks() //throws Exception 
        {
            UpdateStockData();
            return _stocks;
        }

        public void AddAStockForTesting(Stock stock)
        {
            _stocks.add(stock);
        }

        private void UpdateStockData() //throws Exception 
        {
            String url = BuildURL();
            LinkedList<String> dataLines = getDataFromURL(url);
            foreach (Stock stock in _stocks)
            {
                String dataLine = null;
                foreach (String line in dataLines)
                {
                    if (line.startsWith("\"" + stock.getTicker()))
                    {
                        dataLine = line;
                        break;
                    }
                }
                if (dataLine != null)
                {
                    stock.UpdateData(dataLine);
                }
            }
        }

        private String BuildURL()
        {
            StringBuffer url = new StringBuffer();
            url.append(@"http://download.finance.yahoo.com/d/quotes.csv?s=");
            bool first = true;
            foreach (Stock stock in _stocks)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    url.append(",");
                }
                url.append(stock.getTicker());
            }
            url.append("&f=sl1d1t1c1ohgv&e=.csv");
            return url.toString();
        }

        private LinkedList<String> getDataFromURL(String url) //throws MalformedURLException, IOException 
        {
            URLConnection urlc = new URL(url).openConnection();
            BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
            StringBuffer builder = new StringBuffer();
            int byteRead;
            while ((byteRead = buffer.read()) != -1)
            {
                builder.append((char)byteRead);
            }
            buffer.close();
            LinkedList<String> lines = new LinkedList<String>();
            foreach (String line in builder.toString().Split("\r\n".ToCharArray()))
            {
                lines.add(line);
            }
            return lines;
        }

        //@SuppressWarnings("unchecked")
        //@Executable
        public void AddAStock(String ticker) //throws Exception 
        {
            var stockContainer = _containerManager.GetContainer(typeof(Stock).getClass());
            Stock stock = stockContainer.NewPersistentInstance() as Stock;
            stock.setTicker(ticker);
            _stocks.add(stock);
            stockContainer.ObjectChanged(stock);
            _containerManager.GetContainer(typeof(Portfolio).getClass()).ObjectChanged(this);
        }
    }
}
